package cn.edu.sjtu.process_management.interceptor;

import cn.edu.sjtu.process_management.exception.model.RequestException;
import cn.edu.sjtu.process_management.constant.RespStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author loumoon
 * @date 2019-11-08 09:44
 */
public class HostInterceptor implements HandlerInterceptor {

    @Value("${gateway.host}")
    private String gatewayHost;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法则直接通过，防止奇怪的报错
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 检查请求是否来自网关的转发
        String xfh = request.getHeader("x-forwarded-host");
        if(xfh == null || !xfh.equals(gatewayHost)) {
            throw new RequestException(RespStatus.REQUEST_NOT_FROM_GATEWAY);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception e) throws Exception {
    }
}
